package com.shapawan.tourism.security;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 * 用于在每次请求时验证JWT token并设置安全上下文
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        String requestURI = request.getRequestURI();

        log.info("过滤请求: {}", requestURI);

        // 跳过认证的路径
        if (requestURI.contains("/auth/") ||
                requestURI.contains("/public/") ||
                requestURI.contains("/admin/") ||
                requestURI.contains("/swagger") ||
                requestURI.contains("/doc.html") ||
                requestURI.contains("/webjars/") ||
//                requestURI.contains("/locations/") ||
//                requestURI.contains("/locationTypes/") ||
                requestURI.contains("/upload/") ||
                requestURI.contains("/v2/") ||
                requestURI.contains("/v3/")) {
            log.info("路径: {} 无需认证，跳过", requestURI);
            chain.doFilter(request, response);
            return;
        }

        // 从请求头中获取token
        final String requestHeader = request.getHeader("Authorization");
        String username = null;
        String jwtToken = null;

        // 判断token是否存在和是否以"Bearer "开头
        // System.out.println("requestHeader: " + requestHeader);
        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
            jwtToken = requestHeader.substring(7);
            try {
                username = jwtTokenProvider.getUsernameFromToken(jwtToken);
            } catch (IllegalArgumentException e) {
                log.error("获取用户名失败");
            } catch (ExpiredJwtException e) {
                log.warn("token已过期");
            } catch (SignatureException e) {
                log.error("认证失败. token签名校验不通过");
            } catch (MalformedJwtException e) {
                log.error("token格式错误");
            }
        } else {
            log.warn("没有找到token或token格式不正确");
        }

        // 验证token
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // 如果token有效，则进行身份验证
            if (jwtTokenProvider.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                log.info("已认证用户 {}, 设置安全上下文", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        chain.doFilter(request, response);
    }
} 